<?php
/**
 * Model classe
 * @package Core
 * @subpackage Model
 * @author kovacsricsi
 */
class Model implements IModel
{
    /**
     * Name of database table.
     * @access protected
     * @var string
     */
    protected $_tableName;

    /**
     * List of fields name.
     * @access protected
     * @var array
     */
    protected $_columns;

	/**
	 * Name of Entity class, if developer want to use own entity
	 * @access protected
	 * @var string
	 */
	protected $_entity;

	/**
	 * Constructor.
	 * @access public
     * @param string $tableName
	 * @return void
	 */
	public function __construct($tableName, $entity = "Entity")
	{
	    $this->_tableName = (string)$tableName;
		$this->_entity    = $entity;
	    $this->_columns   = QueryHandler::getAll("SHOW COLUMNS FROM " . $this->_tableName);
	}
	
	/**
	 * Returns with entities.
	 * @access public
	 * @param array $where
	 * @param array $order
	 * @param array $limit
	 * @return array
	 */
	public function getAll(array $where = array(), array $order = array(), array $limit = array())
	{
		$entities = array();

		$where[] = "1";

		$ids = $this->_selectAllEntityId($where, $order, $limit);

		foreach($ids as $id) {
			try {
				$entities[] = $this->getOne($id["id"]);
			} catch (Exception $e) {
				BasicErrorHandler::trace($e->getMessage());
			}
		}

		return $entities;
	}

	/**
	 * Returns entity id from database by parameters.
	 * @access public
	 * @param array $id
	 * @return AEntity
	 */
	public function getOne($id)
	{
		$entity = $this->_entity;
		return new $entity($this->_tableName, $this->_columns, $id);
	}

	/**
	 * Returns new empty entity.
	 * @access public
	 * @return AEntity
	 */
	public function getNew()
	{
		$entity = $this->_entity;
		return new $entity($this->_tableName, $this->_columns);
	}

	/**
	 * Returns the max number of results.
	 * @access public
	 * @param array $where
	 * @return integer
	 */
	public function countMax(array $where = array())
	{
		$where[] = "1";

		$result = $this->_selectAllEntityId($where);

		return count($result);
	}

	/**
	 * Returns with entities id.
	 * @access protected
	 * @param array $where
	 * @param array $order
	 * @param array $limit
	 * @return array
	 */
	protected function _selectAllEntityId(array $where = array(), array $order = array(), array $limit = array())
	{
	   $query = "SELECT id FROM " . $this->_tableName;

		$query .= " WHERE (" . join(") AND (", $where) . ")" ;

		if ($order == true) {
			$query .= " ORDER BY " . join(",", $order);
		}

		if ($limit == true) {
			$query .= " LIMIT " . join(",", $limit);
		}

		return QueryHandler::getAll($query);
	}

	/**
	 * Returns with name of the table the modell works with.
	 * @access public
	 * @return string
	 */
	public function getTableName()
	{
		return $this->_tableName;
	}

	/**
	 * Returns with columns.
	 * @access public
	 * @return array
	 */
	public function getColumns()
	{
		return $this->_columns;
	}
}

?>
